#ifndef __SPIN_LOCK_H__
#define __SPIN_LOCK_H__
namespace share
{

// This part is Platform dependent!
#ifdef WIN32

inline void AtomicSwap( int* x, volatile int* X )
{
	__asm
	{
		mov esi, x
		mov eax, dword ptr[ esi ]
		mov edx, X
		lock xchg eax, dword ptr[ edx ]
		mov dword ptr[ esi ], eax
	}
}

#elif (defined(i386) && defined(__GNUC__)) || defined(__INTEL_COMPILER)

inline void AtomicSwap( int* x, volatile int* X )
{
	__asm__ __volatile__( "lock; xchgl %1, %0 " :"=a"( *x ) : "m"( *X ), "a"( *x ) );
}

#endif //GNUC

class SpinLock
{
	public:
	inline SpinLock( ) : lock_( 0 ) {}
	inline ~SpinLock( ) {}

	inline void acquire( void )
	{
		int localLock = 1;

		do
		{
			AtomicSwap( &localLock, &lock_ );
		}
		while( localLock );
	}

	inline void release( void )
	{
		lock_ = 0;
	}
	private:
	SpinLock( const SpinLock& );
	SpinLock& operator= ( const SpinLock& );

	private:
	volatile int lock_;
};

}
#endif


